package com.example.administrator.zhjt;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

import com.example.administrator.zhjt.bean.Event;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by Administrator on 2017/5/18 0018.
 */

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        if (!isNetworkAvailable(context)){
           Toast.makeText(context, "当前有可用网络", Toast.LENGTH_SHORT).show();
        }else  {
            Toast.makeText(context, "当前无可用网络", Toast.LENGTH_SHORT).show();
            EventBus.getDefault().post(new Event(Event.Type.NO_NETWORK,"当前无可用网络"));
         }
    }

    public boolean isNetworkAvailable(Context context){
        ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager==null){
            return false;
        }else {
            NetworkInfo[] networkInfos=connectivityManager.getAllNetworkInfo();
            if (networkInfos!=null&&networkInfos.length>0){
                for (int i=0;i<networkInfos.length;i++){
                    if (networkInfos[i].getState()==NetworkInfo.State.CONNECTED){
                        return true;
                    }
                }
            }
        }
        return false;
    }

}
